package net.wenku8.reader.service

import com.alibaba.fastjson2.JSON
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import net.wenku8.reader.api.BookApi
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.model.book.Chapter
import net.wenku8.reader.model.book.Volume

class BookCacheService {

    companion object {
        private val workMap = HashMap<String, Job>()

        fun addWorker(bookId : String){
            if (workMap.contains(bookId)) return
            val job = CoroutineScope(Dispatchers.IO).launch {
                cacheBook(bookId)
            }
            workMap[bookId] = job
        }

        private fun cacheBook(bookId : String){
            val bookInfoResp = BookApi.getBookInfo(bookId)
            if (ApiResult.isSuccess(bookInfoResp)){
                FileService.writeFile("/wenku8/offline/info/book$bookId", JSON.toJSONString(bookInfoResp.data))
            }else{
                return
            }
            val bookVolumeResp = BookApi.getBookVolume(bookId)
            if (ApiResult.isSuccess(bookVolumeResp)){
                FileService.writeFile("/wenku8/offline/volume/book$bookId", JSON.toJSONString(bookVolumeResp.data))
            }else{
                return
            }
            bookVolumeResp.data?.forEach { volume: Volume ->
                volume.chapterList?.forEach { chapter: Chapter? ->
                    if (chapter == null || chapter.chapterId == null) return
                    val chapterId = chapter.chapterId
                    val apiResult = BookApi.getBookText(bookId, chapterId)
                    if (ApiResult.isSuccess(bookVolumeResp)){
                        FileService.writeFile("/wenku8/offline/text/text$chapterId", JSON.toJSONString(apiResult.data))
                    }
                }
            }

        }

    }
}